package co.fitstart.admin.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.core.persistence.GenericDaoSupport;

import co.fitstart.admin.service.CoursewareTestService;
import co.fitstart.entity.courseware.fitnessgroup.BatchCoursewareTemplate;
import co.fitstart.entity.courseware.fitnessgroup.CoursewareTemplate;
import co.fitstart.entity.courseware.fitnessgroup.DailyCoursewareTemplate;
import co.fitstart.entity.courseware.fitnessgroup.FitnessGroup;

@Service("coursewareTestService")
public class CoursewareTestServiceImpl implements CoursewareTestService{
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;

    /*
     * (non-Javadoc)
     * @see co.fitstart.admin.service.CoursewareTestService#changeGroup(co.fitstart.entity.courseware.fitnessgroup.FitnessGroup, co.fitstart.entity.courseware.fitnessgroup.FitnessGroup)
     */
    @SuppressWarnings("unchecked")
    public void changeGroup(FitnessGroup group, FitnessGroup change) {
        
        List<BatchCoursewareTemplate> batches = genericDaoSupport.searchForList("FROM BatchCoursewareTemplate WHERE disabled = false AND fitnessGroup = :fitnessGroup AND type = 0 ORDER BY sorting", "fitnessGroup", group);
        List<BatchCoursewareTemplate> changeBatches = genericDaoSupport.searchForList("FROM BatchCoursewareTemplate WHERE disabled = false AND fitnessGroup = :fitnessGroup AND type = 0 AND sorting < 7 ORDER BY sorting", "fitnessGroup", change);
        
        for(int i=0; i<batches.size(); i++) {
            genericDaoSupport.update(changeBatches.get(i).edit(batches.get(i)));
            
            List<DailyCoursewareTemplate> dailies = genericDaoSupport.searchForList("FROM DailyCoursewareTemplate WHERE disabled = false AND batch = :batch ORDER BY sorting", "batch", batches.get(i));
            List<DailyCoursewareTemplate> changeDailies = genericDaoSupport.searchForList("FROM DailyCoursewareTemplate WHERE disabled = false AND batch = :batch ORDER BY sorting", "batch", changeBatches.get(i));
            for(int j=0; j<dailies.size(); j++) {
                genericDaoSupport.update(changeDailies.get(j).edit(dailies.get(j)));
                
                List<CoursewareTemplate> coursewares = genericDaoSupport.searchForList("FROM CoursewareTemplate WHERE disabled = false AND daily = :daily", "daily", dailies.get(j));
                for(CoursewareTemplate courseware : coursewares) {
                    genericDaoSupport.save(new CoursewareTemplate(courseware, changeDailies.get(j)));
                }
            }
        }
        
        
        
        
    }
    
}
